<?php
    require('common.php');
        
    $db = new Database();
    $user = getUser($db);
    
    // Error check
    if($user['group'] != 0)
        throw new Exception('Already logged in.');
    if(!isset($_POST['user']) || !isset($_POST['password']) || !isset($_POST['redirect']))
        throw new Exception('Bad request.');
        
    // Get the user information and check that user exists
    $result = $db->query('SELECT salt, password, id, name FROM '.
        config('DB_PREFIX').'users WHERE name='.
        $db->escape($_POST['user']));
    if(mysqli_num_rows($result) == 0) {
        message(lang('BAD_LOGIN'), 'login.php', lang('BACK_TO_LOGIN'));
        exit();
    }
    $result = mysqli_fetch_assoc($result);
    $salt = $result['salt'];
    $password = $result['password'];
    $id = $result['id'];
    $name = $result['name'];
    
    // Check the password
    if(sha1($salt.$_POST['password']) != $password) {
        message(lang('BAD_LOGIN'), 'login.php', lang('BACK_TO_LOGIN'));
        exit();
    }
    
    // Set the cookie 
    setcookie('user_id', $id, time() + 86400*365);
    setcookie('password', sha1($salt.$_POST['password']), time() + 86400*365);
    
    // Redirect
    $redirect = preg_replace('#[^A-Za-z0-9\\.\\?&/=]#', '', urldecode($_POST['redirect']));
    redirect($redirect);
?>